package com.ls.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.config.satoken.SaTokenUtilPy;
import com.ls.controller.rule.model.*;
import com.ls.entity.*;
import com.ls.enums.CallTypeEnum;
import com.ls.enums.RoleEnum;
import com.ls.exception.SysException;
import com.ls.mapper.SmsRuleMapper;
import com.ls.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.utils.ResultData;
import com.nlf.calendar.Lunar;
import com.nlf.calendar.Solar;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.ls.constant.SystemConstants.*;
import com.ls.utils.pay.TimeUtils;
/**
 * <p>
 * 短信规则，通话方式-规则 一对多 （不同规则不能包含相同的时间段）互斥 。规则-模板 一对多。 服务实现类
 * </p>
 *
 * @author pengyu
 * @since 2024-06-28
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SmsRuleServiceImpl extends ServiceImpl<SmsRuleMapper, SmsRule> implements ISmsRuleService {

    private final ISmsTemplateService templateService;
    private final IRuleTemplateService ruleTemplateService;
    private final ITeamService teamService;
    private final ILabelService labelService;
    private final ILinkmanService linkmanService;
    private final IRuleLinkmanService ruleLinkmanService;
    private final IHolidayService holidayService;

    /**
     * 新增短信规则
     */
    @Transactional(rollbackFor = SysException.class)
    @Override
    public ResultData add(AddRuleModel model) {
        log.info("add model:" + model.toString());
        Customer customer = SaTokenUtilPy.getCustomer();
        Long customerId = customer.getCustomerId();
        if (model.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP) {
            if (model.getCallType() == null) {
                return ResultData.failure("请选择呼叫方式！");
            }
            if (model.getEndTime() == null) {
                return ResultData.failure("请选择结束时间！");
            }
            if (model.getLimitType() == null) {
                return ResultData.failure("请选择限制类型！");
            }
        } else {
            if (model.getHolidayId() == null) {
                return ResultData.failure("请选择节日！");
            }
            if (model.getAdvance() == null) {
                return ResultData.failure("请选择提前时间！");
            }
            if (model.getTeamId()==null&&model.getTeamId()==null&&model.getLinkmanId().size()<=0){
                return ResultData.failure("请选择联系人！");
            }
        }
        //查询当前用户所有短信规则的数量
        Long count = (long) count(new LambdaQueryWrapper<SmsRule>()
                .eq(model.getCallType() != null, SmsRule::getCallType, model.getCallType())
                .eq(SmsRule::getTemplateCategory, model.getTemplateCategory())
                .eq(model.getHolidayId() != null, SmsRule::getHolidayId, model.getHolidayId())
                .eq(SmsRule::getCustomerId, customerId)
        );
        //判断当前规则的限制是否有重复
        log.info("count非会员:" + count);
        RoleEnum roleEnum = RoleEnum.getRoleEnum(customer.getRoleId());
        if (model.getCallType() != null) {
            CallTypeEnum callTypeEnum = CallTypeEnum.getRoleEnum(model.getCallType());
            if (model.getCallType() != null && CallTypeEnum.IN_NOT_DISTURB.equals(callTypeEnum) && RoleEnum.COMMON.equals(roleEnum)) {
                return ResultData.noPermission("非会员不能新增勿扰规则！");
            }
        }
        if (RoleEnum.COMMON.equals(roleEnum) && count > 0) {
            return ResultData.noPermission(" 非会员只能新增一个规则！");
        }
        if (RoleEnum.COMMON.equals(roleEnum) && model.getTemplateIdArray().length > 1) {
            return ResultData.noPermission("非会员只能单选模板！");
        }
        if (model.getCallType() != null && checkTimeOverlap(customerId, model.getCallType(), model.getStartTime(), model.getEndTime(), null)) {
            return ResultData.failure("时间段与已有规则冲突，请调整时间范围");
        }
        Long[] templateIdArray = model.getTemplateIdArray();
        List<Long> templateIdList = new ArrayList<>(Arrays.asList(templateIdArray));
        List<SmsTemplate> smsTemplateList = templateService.listByIds(templateIdList);
        if (CollectionUtils.isEmpty(smsTemplateList)) {
            return ResultData.failure("模板id在库里不存在：");
        }
        String ruleName = model.getRuleName();
        //按 customerId 和 ruleName 校验是否重复
        SmsRule smsRule;
        if (model.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP) {
            smsRule = getByCustomerAndName(customerId, ruleName, TEMPLATE_CATEGORY_HANG_UP, model.getCallType(), null);
        } else {
            smsRule = getByCustomerAndName(customerId, ruleName, TEMPLATE_CATEGORY_CARE, null, model.getHolidayId());
        }
        if (smsRule != null) {
            return ResultData.failure("当前规则名称已经存在，请修改后提交：" + ruleName);
        }
//        model.getStartTime().isAfter(model.getEndTime())||
        //考虑到00：00到00：00点时的跨天判断，设置开始时间不能等于结束时间
        if (model.getStartTime() == model.getEndTime()) {
            return ResultData.failure("开始时间不能等于结束时间，请修改后提交：");
        }
        LocalDateTime now = LocalDateTime.now();
        smsRule = new SmsRule();
        if (model.getTemplateCategory()==TEMPLATE_CATEGORY_CARE){
            //rule保存CareRuleModel
            CareRuleModel careRuleModel = new CareRuleModel();
            BeanUtils.copyProperties(model, careRuleModel);
            BeanUtils.copyProperties(careRuleModel, smsRule);
        }else {
            HangUpRuleModel hangUpRuleModel = new HangUpRuleModel();
            BeanUtils.copyProperties(model, hangUpRuleModel);
            BeanUtils.copyProperties(hangUpRuleModel, smsRule);
        }
        smsRule.setCreateTime(now);
        smsRule.setUpdateTime(now);
        smsRule.setCustomerId(customerId);
        smsRule.setValidFlag(VALID_TRUE);
        smsRule.setPhone(customer.getPhone());
        save(smsRule);
        String phone = customer.getPhone();
        Long ruleId = smsRule.getRuleId();
        for (SmsTemplate template : smsTemplateList) {
            RuleTemplate ruleTemplate;
            ruleTemplate = ruleTemplateService.getOnly(ruleId, template.getTemplateId());
            if (ruleTemplate != null) {
                continue;
            }
            ruleTemplate = new RuleTemplate();
            ruleTemplate.setCustomerId(customerId);
            ruleTemplate.setRuleId(ruleId);
            ruleTemplate.setTemplateId(template.getTemplateId());
            ruleTemplate.setCreateTime(now);
            ruleTemplate.setPhone(phone);
            ruleTemplateService.save(ruleTemplate);
        }
        if (model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE) {
            //设置一个数组
            List<Long> teamIdArray = new ArrayList<>();
            List<Long> teamIdList = new ArrayList<>();
            if (model.getTeamType() != null || model.getTeamId() != null) {
                teamIdList = teamService.list(new LambdaQueryWrapper<Team>()
                        .eq(Team::getCustomerId, customerId)
                        .eq(Team::getValidFlag, VALID_TRUE)
                        .in(model.getTeamType() != null, Team::getTeamType, model.getTeamType())
                        .in(model.getTeamId() != null, Team::getTeamId, model.getTeamId())
                ).stream().map(Team::getTeamId).collect(Collectors.toList());
            }
            List<Long> labelIdList = new ArrayList<>();
            if (model.getTeamId() != null || model.getTeamType() != null) {
                labelIdList = labelService.list(new LambdaQueryWrapper<Label>()
                        .eq(Label::getCustomerId, customerId)
                        .eq(Label::getValidFlag, VALID_TRUE)
                        .in(model.getLabelType() != null, Label::getLabelType, model.getLabelType())
                        .in(model.getLabelId() != null, Label::getLabelId, model.getLabelId())
                ).stream().map(Label::getLabelId).collect(Collectors.toList());
            }
            List<Long> linkmanIdList = linkmanService.list(new LambdaQueryWrapper<Linkman>()
                            .eq(Linkman::getCustomerId, customerId)
                            .eq(Linkman::getValidFlag, VALID_TRUE)
                            .in(model.getLinkmanId() != null, Linkman::getLinkmanId, model.getLinkmanId())
//                    .in(teamIdList.size() > 0, Linkman::getTeamId, teamIdList)
//                    .in(labelIdList.size() > 0, Linkman::getLabelId, labelIdList)
            ).stream().map(Linkman::getLinkmanId).collect(Collectors.toList());
            log.info("linkmanIdList新增:{}" + linkmanIdList);
            linkmanIdList.forEach(linkmanId -> {
                RuleLinkman ruleLinkman = new RuleLinkman();
                ruleLinkman.setCustomerId(customerId);
                ruleLinkman.setRuleId(ruleId);
                ruleLinkman.setPhone(phone);
                ruleLinkman.setLinkmanId(linkmanId);
                ruleLinkman.setCreateTime(now);
                ruleLinkmanService.save(ruleLinkman);
            });
        }
        return ResultData.success();
    }

    private boolean checkTimeOverlap(Long customerId, Integer callType, LocalTime newStart, LocalTime newEnd, Long ruleId) {
        List<SmsRule> existingRules = list(new LambdaQueryWrapper<SmsRule>()
                .eq(SmsRule::getCustomerId, customerId)
                .ne(ruleId != null, SmsRule::getRuleId, ruleId)
                .eq(SmsRule::getValidFlag, VALID_TRUE)
                .eq(SmsRule::getCallType, callType));

        return existingRules.stream().anyMatch(rule ->
                (newStart.isBefore(rule.getEndTime()) && newEnd.isAfter(rule.getStartTime())) ||
                        (rule.getStartTime().isBefore(newEnd) && rule.getEndTime().isAfter(newStart))
        );
    }

    /**
     * 编辑短信规则
     */
    @Transactional(rollbackFor = SysException.class)
    @Override
    public ResultData edit(EditRuleModel model) {
        log.info("修改规则model:{}",model);
        LocalDateTime now = LocalDateTime.now();
        Long ruleId = model.getRuleId();
        SmsRule rule = getById(ruleId);
        if (rule == null) {
            log.error("ruleId 不在库里:" + ruleId);
            return ResultData.failure("ruleId 不在库里");
        }
        if (model.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP) {
            if (model.getCallType() == null) {
                return ResultData.failure("请选择呼叫方式！");
            }
            if (model.getEndTime() == null) {
                return ResultData.failure("请选择结束时间！");
            }
            if (model.getLimitType() == null) {
                return ResultData.failure("请选择限制类型！");
            }

        } else {
            if (model.getHolidayId() == null) {
                return ResultData.failure("请选择节日！");
            }
            if (model.getAdvance() == null) {
                return ResultData.failure("请选择提前时间！");
            }
            if (model.getTeamId()==null&&model.getTeamId()==null&&model.getLinkmanId().size()<=0){
                return ResultData.failure("请选择联系人！");
            }
        }
        Long customerId = rule.getCustomerId();
        Customer customer = SaTokenUtilPy.getCustomer();
        Long customerIdFromRedis = customer.getCustomerId();
        log.info("customerIdFromRedis:" + customerIdFromRedis);
        if (!customerId.equals(customerIdFromRedis)) {
            log.error("规则和当前操作员不匹配，请联系管理员：" + ruleId);
            return ResultData.failure("规则和当前操作员不匹配，请联系管理员：");
        }
        RoleEnum roleEnum = RoleEnum.getRoleEnum(customer.getRoleId());
        if (RoleEnum.COMMON.equals(roleEnum) && model.getTemplateIdArray().length > 1) {
            return ResultData.noPermission("非会员只能单选模板！");
        }
        String phone = customer.getPhone();
        if (rule.getValidFlag() == VALID_TRUE && checkTimeOverlap(customerId, model.getCallType(), model.getStartTime(), model.getEndTime(), ruleId)) {
            return ResultData.failure("时间段与已有规则冲突，请调整时间范围");
        }

        //判断规则名称是否修改
        String ruleName = model.getRuleName();
        if (!rule.getRuleName().equals(ruleName)) {
            SmsRule ruleCheck;
            if (model.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP) {
                ruleCheck = getByCustomerAndName(customerId, ruleName, TEMPLATE_CATEGORY_HANG_UP, model.getCallType(), null);
            } else {
                ruleCheck = getByCustomerAndName(customerId, ruleName, TEMPLATE_CATEGORY_CARE, null, model.getHolidayId());
            }
            if (ruleCheck != null) {
                return ResultData.failure("规则名称已经存在，请修改后再提交：");
            }
        }
        //考虑到00：00到00：00点时的跨天判断，设置开始时间不能等于结束时间
        if (model.getStartTime() == model.getEndTime()) {
            return ResultData.failure("开始时间不能等于结束时间，请修改后提交：");
        }

        if (model.getTemplateCategory()==TEMPLATE_CATEGORY_CARE){
            //rule保存CareRuleModel
            CareRuleModel careRuleModel = new CareRuleModel();
            BeanUtils.copyProperties(model, careRuleModel);
            BeanUtils.copyProperties(careRuleModel, rule);
        }else {
            HangUpRuleModel hangUpRuleModel = new HangUpRuleModel();
            BeanUtils.copyProperties(model, hangUpRuleModel);
            BeanUtils.copyProperties(hangUpRuleModel, rule);
        }
        rule.setUpdateTime(LocalDateTime.now());
        boolean flag = updateById(rule);



        // 直接删除老的关联关系，然后insert ruleTemplateService
        ruleTemplateService.remove(new LambdaQueryWrapper<RuleTemplate>().eq(RuleTemplate::getRuleId, ruleId));
        ruleLinkmanService.remove(new LambdaQueryWrapper<RuleLinkman>().eq(RuleLinkman::getRuleId, ruleId));
        Long[] templateIdArray = model.getTemplateIdArray();
        List<Long> templateIdList = new ArrayList<>(Arrays.asList(templateIdArray));
        List<SmsTemplate> smsTemplateList = templateService.listByIds(templateIdList);
        if (CollectionUtils.isEmpty(smsTemplateList)) {
            return ResultData.failure("模板id在库里不存在：");
        }
        // 循环插入
        for (SmsTemplate template : smsTemplateList) {
            RuleTemplate ruleTemplate;
            ruleTemplate = ruleTemplateService.getOnly(ruleId, template.getTemplateId());
            if (ruleTemplate != null) {
                continue;
            }
            ruleTemplate = new RuleTemplate();
            ruleTemplate.setCustomerId(customerIdFromRedis);
            ruleTemplate.setRuleId(ruleId);
            ruleTemplate.setTemplateId(template.getTemplateId());
            ruleTemplate.setCreateTime(now);
            ruleTemplate.setPhone(phone);
            ruleTemplateService.save(ruleTemplate);
            log.info("修改规则:{}" + ruleTemplate);

        }
        if (model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE) {
            //设置一个数组
            Long[] teamIdArray = null;
            List<Long> teamIdList = teamService.list(new LambdaQueryWrapper<Team>()
                    .eq(Team::getCustomerId, customerId)
                    .eq(Team::getValidFlag, VALID_TRUE)
                    .in(model.getTeamType() != null, Team::getTeamType, model.getTeamType())
                    .in(model.getTeamId() != null, Team::getTeamId, model.getTeamId())
            ).stream().map(Team::getTeamId).collect(Collectors.toList());
            List<Long> labelIdList = labelService.list(new LambdaQueryWrapper<Label>()
                    .eq(Label::getCustomerId, customerId)
                    .eq(Label::getValidFlag, VALID_TRUE)
                    .in(model.getLabelType() != null, Label::getLabelType, model.getLabelType())
                    .in(model.getLabelId() != null, Label::getLabelId, model.getLabelId())
            ).stream().map(Label::getLabelId).collect(Collectors.toList());
            log.info("model.getLinkmanId()新增:{}" ,model.getLinkmanId());
            log.info("teamIdList新增:{}",teamIdList.size());
            log.info("teamIdList新增:{}",labelIdList.size());
            List<Long> linkmanIdList = linkmanService.list(new LambdaQueryWrapper<Linkman>()
                            .eq(Linkman::getCustomerId, customerId)
                            .eq(Linkman::getValidFlag, VALID_TRUE)
                            .in(model.getLinkmanId() != null, Linkman::getLinkmanId, model.getLinkmanId())
//                    .in(teamIdList.size() > 0, Linkman::getTeamId, teamIdList)
//                    .in(labelIdList.size() > 0, Linkman::getLabelId, labelIdList)
            ).stream().map(Linkman::getLinkmanId).collect(Collectors.toList());
            log.info("linkmanIdList新增:{}" + linkmanIdList);
            linkmanIdList.forEach(linkmanId -> {
                log.info("ruleLinkman:{}", linkmanId);
                RuleLinkman ruleLinkman = new RuleLinkman();
                ruleLinkman.setCustomerId(customerId);
                ruleLinkman.setRuleId(ruleId);
                ruleLinkman.setPhone(phone);
                ruleLinkman.setLinkmanId(linkmanId);
                ruleLinkman.setCreateTime(now);
                ruleLinkmanService.save(ruleLinkman);
            });
        }

        if (flag) {
            return ResultData.success();
        } else {
            return ResultData.failure("数据库错误");
        }
    }

    /**
     * 删除短信规则
     */
    @Override
    public ResultData del(Long ruleId) {
        SmsRule rule = getById(ruleId);
        if (rule == null) {
            log.error("ruleId 不在库里:" + ruleId);
            return ResultData.failure("模板已经不在库里");
        }
        Long customerId = rule.getCustomerId();
        Long customerIdFromRedis = StpUtil.getLoginIdAsLong();
        log.info("customerIdFromRedis:" + customerIdFromRedis);
        if (!customerId.equals(customerIdFromRedis)) {
            log.error("规则和当前操作员不匹配，请联系管理员：" + ruleId);
            return ResultData.failure("规则和当前操作员不匹配，请联系管理员：");
        }
        //关怀短信规则移除绑定联系人
        if (rule.getTemplateCategory()==TEMPLATE_CATEGORY_CARE){
            ruleLinkmanService.remove(new LambdaQueryWrapper<RuleLinkman>().eq(RuleLinkman::getRuleId, ruleId));
        }
        // 删除关联关系
        ruleTemplateService.remove(new LambdaQueryWrapper<RuleTemplate>().eq(RuleTemplate::getRuleId, ruleId));
        boolean flag = removeById(ruleId);
        if (flag) {
            return ResultData.success();
        } else {
            return ResultData.failure("数据库错误");
        }
    }

    /**
     * 分页查询短信规则
     */
    @Override
    public ResultData pageList(QueryRuleModel model) {
        log.info("分页查询短信规则:{}", model);
        Customer customer = SaTokenUtilPy.getCustomer();
        Long customerId = customer.getCustomerId();
        List<Long> holidayIds = new ArrayList<>();
        //通过categoryId查询
        if (model.getCategoryId() != null) {
            log.info("通过categoryId查询:{}", model.getCategoryId());
            List<Holiday> holidayList = new ArrayList<>();
            if (model.getCategoryId() == 1) {
                holidayList = holidayService.list(new LambdaQueryWrapper<Holiday>()
                        .in(Holiday::getCategoryId, Arrays.asList(1, 2, 3, 4))
                        .eq(Holiday::getValidFlag, VALID_TRUE)
                        .orderByDesc(Holiday::getCreateTime)
                );
                log.info("获取所有节假日id:{}", holidayIds);
            } else if (model.getCategoryId() == 2) {
                holidayIds.add(6L);
            } else {
                holidayList = holidayService.list(new LambdaQueryWrapper<Holiday>()
                        .eq(Holiday::getCategoryId, model.getCategoryId())
                        .eq(Holiday::getValidFlag, VALID_TRUE)
                        .orderByDesc(Holiday::getCreateTime)
                );
            }
            if (model.getCategoryId() != 2) {
                holidayIds = Optional.ofNullable(holidayList)
                        .orElse(Collections.emptyList())
                        .stream()
                        .map(Holiday::getHolidayId)
                        .collect(Collectors.toList());
            }
        }
        //通过childCategoryId查询
        if (model.getChildCategoryId()!=null){
            log.info("通过childCategoryId查询:{}", model.getChildCategoryId());
            List<Holiday> holidayList = new ArrayList<>();
            holidayList = holidayService.list(new LambdaQueryWrapper<Holiday>()
                    .eq(Holiday::getCategoryId, model.getChildCategoryId())
                    .eq(Holiday::getValidFlag, VALID_TRUE)
                    .orderByDesc(Holiday::getCreateTime)
            );
            holidayIds = Optional.ofNullable(holidayList)
                    .orElse(Collections.emptyList())
                    .stream()
                    .map(Holiday::getHolidayId)
                    .collect(Collectors.toList());
        }
        log.info("获取所有节假日id:{}", holidayIds);
        //联系人内的关联事件
        List<Long> linkmanIdList1=new ArrayList<>();
        if (model.getLinkmanId()!=null){
            linkmanIdList1 = ruleLinkmanService.list(new LambdaQueryWrapper<RuleLinkman>()
                    .eq(RuleLinkman::getCustomerId, customerId)
                    .eq(RuleLinkman::getLinkmanId, model.getLinkmanId())
            ).stream().map(RuleLinkman::getRuleId).collect(Collectors.toList());
        }
        //1 查询出规则列表
        LambdaQueryWrapper<SmsRule> wrapper = new LambdaQueryWrapper<SmsRule>()
                .eq(SmsRule::getCustomerId, customer.getCustomerId())
                .in(model.getLinkmanId()!=null&& model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE&&linkmanIdList1.size()>0,SmsRule::getRuleId,linkmanIdList1)
                .eq(model.getLinkmanId() != null&& model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE&&linkmanIdList1.size()==0,SmsRule::getRuleId,-1)
                .eq(StringUtils.isNotBlank(model.getPhone()), SmsRule::getPhone, model.getPhone())
                .eq(model.getCallType() != null, SmsRule::getCallType, model.getCallType())
                .eq(model.getHolidayId() != null, SmsRule::getHolidayId, model.getHolidayId())
                .eq(SmsRule::getTemplateCategory, model.getTemplateCategory())
                .in(model.getCategoryId() != null  && holidayIds.size() > 0||model.getChildCategoryId() != null&&holidayIds.size() > 0,
                        SmsRule::getHolidayId, holidayIds)
                .eq(model.getCategoryId() != null  && holidayIds.size() == 0||model.getChildCategoryId() != null&&holidayIds.size() == 0,
                        SmsRule::getHolidayId, -1)
                .orderByDesc(SmsRule::getValidFlag)
                .orderByDesc(SmsRule::getRuleId);
        Page page = new Page(model.getPageNum(), model.getPageSize());
        IPage<SmsRule> dtoIPage = this.baseMapper.selectPage(page, wrapper);
        List<SmsRule> ruleList = dtoIPage.getRecords();
        if (CollectionUtils.isEmpty(ruleList)) {
            // 创建新的返回数据结构
            Map<String, Object> resultMap = new LinkedHashMap<>();
            resultMap.put("enabledCount", 0);
            resultMap.put("records", dtoIPage.getRecords());
            resultMap.put("total", dtoIPage.getTotal());
            resultMap.put("size", dtoIPage.getSize());
            resultMap.put("current", dtoIPage.getCurrent());
            resultMap.put("pages", dtoIPage.getPages());
            return ResultData.successData(resultMap);
        }
        if (ruleList.size() > 0) {
            //2 每个规则查询出最后一个短信模板以及模板对应的内容
            ruleList.forEach(rule -> {
                log.info("rule:{}", rule);
//                SmsRuleAppVo vo = new SmsRuleAppVo();
//                BeanUtils.copyProperties(rule ,vo);
                // 后续业务处理
                List<RuleTemplate> ruleTemplateList = ruleTemplateService.list(new LambdaQueryWrapper<RuleTemplate>().eq(RuleTemplate::getRuleId, rule.getRuleId()).orderByDesc(RuleTemplate::getId));
                if (CollectionUtils.isNotEmpty(ruleTemplateList)) {
                    List<SmsTemplate> smsTemplateList = new ArrayList<>();
                    for (RuleTemplate ruleTemplate : ruleTemplateList) {
                        SmsTemplate template = templateService.getById(ruleTemplate.getTemplateId());
                        if (template != null) {
                            smsTemplateList.add(template);
                        }
                    }
                    // 设置模板信息到 SmsRule 中
                    rule.setTemplateList(smsTemplateList);
                }
                log.info("rule:{}", rule.getRuleId());
                if (model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE) {
                    List<Long> linkmanIdList = ruleLinkmanService.list(new LambdaQueryWrapper<RuleLinkman>()
                            .eq(RuleLinkman::getRuleId, rule.getRuleId())
                    ).stream().map(RuleLinkman::getLinkmanId).collect(Collectors.toList());
                    log.info("{}:linkmanIdList:{}",rule.getRuleId(), linkmanIdList);
                    log.info("CollectionUtils.isNotEmpty(linkmanIdList):{}",CollectionUtils.isNotEmpty(linkmanIdList));
                    log.info("linkmanIdList.size()>0:{}",linkmanIdList.size()>0);
                    if (CollectionUtils.isNotEmpty(linkmanIdList)&&linkmanIdList.size()>0) {
                        log.info("----------------");
                        List<Linkman> linkmanList = new ArrayList<>();
                        for (Long linkmanId : linkmanIdList) {
                            Linkman linkman = linkmanService.getById(linkmanId);
                            log.info("linkman:{}", linkman);
                            if (linkman != null) {
                                linkmanList.add(linkman);
                            }
                        }
                        log.info("linkmanList:{}", linkmanList);
                        rule.setLinkmanList(linkmanList);
                    }
                    log.info("rule.getLinkmanList():{}", rule.getLinkmanList());
                    if (rule.getLinkmanList() != null){
                        rule.setLinkmanNum(rule.getLinkmanList().size());
                    }else {
                        rule.setLinkmanNum(0);
                    }
                    String holidayName = holidayService.getById(rule.getHolidayId()).getHolidayName();
                    rule.setHolidayName(holidayName);
                }
            });
        }

        // 修改为泛型兼容的写法
        IPage<Object> resultPage = new Page<>(model.getPageNum(), model.getPageSize());
        BeanUtils.copyProperties(dtoIPage, resultPage, "records");

        List<Object> resultList = ruleList.stream()
                .map(rule -> {
                    if (model.getTemplateCategory() == TEMPLATE_CATEGORY_CARE) {
                        CareRuleModel careModel = new CareRuleModel();
                        BeanUtils.copyProperties(rule, careModel);
                        //排除生日
                        if (rule.getHolidayId() != HOLIDAY_ID_BIRTHDAY) {
                            Holiday holiday = holidayService.getById(rule.getHolidayId());
                            careModel.setNextDay(TimeUtils.getNextExecuteDate(rule.getAdvance(),holiday,LocalDate.now()));
                        }
                        if (careModel.getNextDay()!=null&&careModel.getNextDay().isBefore(LocalDate.now())){
                            careModel.setIsNext(NUMBER_0);
                        }else{
                            careModel.setIsNext(NUMBER_1);
                        }
                        return careModel;
                    } else {
                        HangUpRuleModel hangUpModel = new HangUpRuleModel();
                        BeanUtils.copyProperties(rule, hangUpModel);
                        return hangUpModel;
                    }
                })
                .collect(Collectors.toList());

        resultPage.setRecords(resultList);
        Integer enabledCount = count(wrapper.eq(SmsRule::getValidFlag, VALID_TRUE));
        // 创建新的返回数据结构
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("enabledCount", enabledCount);
        resultMap.put("records", resultPage.getRecords());
        resultMap.put("total", resultPage.getTotal());
        resultMap.put("size", resultPage.getSize());
        resultMap.put("current", resultPage.getCurrent());
        resultMap.put("pages", resultPage.getPages());

        return ResultData.successData(resultMap);
    }

    /**
     * 规则模板详情
     */
    @Override
    public ResultData getRuleById(Long ruleId) {
        SmsRule smsRule = getById(ruleId);
        if (smsRule == null) {
            return ResultData.failure(" 模板Id不在库里：" + ruleId);
        }
        List<RuleTemplate> ruleTemplateList = ruleTemplateService.list(new LambdaQueryWrapper<RuleTemplate>().eq(RuleTemplate::getRuleId, ruleId).orderByDesc(RuleTemplate::getId));
        List<RuleLinkman> ruleLinkmanList = ruleLinkmanService.list(new LambdaQueryWrapper<RuleLinkman>().eq(RuleLinkman::getRuleId, ruleId));
        if (CollectionUtils.isNotEmpty(ruleTemplateList)) {
            List<SmsTemplate> smsTemplateList = new ArrayList<>();
            List<Linkman> linkmanList = new ArrayList<>();
            for (RuleTemplate ruleTemplate : ruleTemplateList) {
                SmsTemplate template = templateService.getById(ruleTemplate.getTemplateId());
                if (template != null) {
                    smsTemplateList.add(template);
                }
            }
            // 设置模板信息到 SmsRule 中
            smsRule.setTemplateList(smsTemplateList);
            for (RuleLinkman ruleLinkman : ruleLinkmanList) {
                Linkman linkman = linkmanService.getById(ruleLinkman.getLinkmanId());
                if (linkman != null) {
                    linkmanList.add(linkman);
                }
            }
            smsRule.setLinkmanList(linkmanList);
        }
        if (smsRule.getTemplateCategory() == TEMPLATE_CATEGORY_CARE) {
            CareRuleVo careVo = new CareRuleVo();
            BeanUtils.copyProperties(smsRule, careVo);
            Holiday holiday = holidayService.getById(smsRule.getHolidayId());
            careVo.setHolidayName(holiday.getHolidayName());
            careVo.setLinkmanNum(smsRule.getLinkmanList().size());
            careVo.setPeriod(holiday.getPeriod());
            careVo.setPeriodCount(holiday.getPeriodCount());
            careVo.setLinkmanList(smsRule.getLinkmanList());
            return ResultData.successData(careVo);
        } else {
            HangUpRuleModel hangUpModel = new HangUpRuleModel();
            BeanUtils.copyProperties(smsRule, hangUpModel);
            return ResultData.successData(hangUpModel);
        }
    }

    private SmsRule getByCustomerAndName(Long customerId, String ruleName, Integer templateCategory, Integer callType, Long holidayId) {
        return getOne(new LambdaQueryWrapper<SmsRule>()
                .eq(SmsRule::getCustomerId, customerId)
                .eq(SmsRule::getRuleName, ruleName)
                .eq(SmsRule::getTemplateCategory, templateCategory)
                .eq(callType != null, SmsRule::getCallType, callType)
                .eq(holidayId != null, SmsRule::getHolidayId, holidayId)
        );
    }

    /**
     * app绑定短信规则
     */
    @Override
    public ResultData bindRuleId(BindRuleIdModel model) {

        if (model == null || model.getRuleId() == null) {
            return ResultData.failure("ruleId 不能为空");
        }
        Long ruleId = model.getRuleId();
        SmsRule smsRule = getById(ruleId);
        if (smsRule.getTemplateCategory() == TEMPLATE_CATEGORY_HANG_UP) {
            Customer customer = SaTokenUtilPy.getCustomer();
            Long customerId = customer.getCustomerId();
            RoleEnum roleEnum = RoleEnum.getRoleEnum(customer.getRoleId());
            CallTypeEnum callTypeEnum = CallTypeEnum.getRoleEnum(smsRule.getCallType());
            if (RoleEnum.COMMON.equals(roleEnum) && CallTypeEnum.IN_NOT_DISTURB.equals(callTypeEnum) && model.getValidFlag() == VALID_TRUE) {
                return ResultData.noPermission("非会员不能绑定此规则");
            }
            Long count = (long) count(new LambdaQueryWrapper<SmsRule>()
                    .eq(SmsRule::getCallType, smsRule.getCallType())
                    .eq(SmsRule::getCustomerId, customerId)
                    .eq(SmsRule::getValidFlag, VALID_TRUE)
            );
            if (count > 0 && RoleEnum.COMMON.equals(roleEnum) && model.getValidFlag() == VALID_TRUE) {
                log.info("非会员不能启用多个规则！,{}", customer);
                return ResultData.noPermission("非会员只能启用一个规则！");
            }
            if (model.getValidFlag() == VALID_TRUE && checkTimeOverlap(customerId, smsRule.getCallType(), smsRule.getStartTime(), smsRule.getEndTime(), smsRule.getRuleId())) {
                return ResultData.failure("时间段与已有规则冲突，请调整时间范围");
            }
        }

        if (smsRule == null) {
            log.error("ruleId 不在库里:" + ruleId);
            return ResultData.failure("ruleId 不在库里");
        }
        smsRule.setValidFlag(model.getValidFlag());

        boolean flag = updateById(smsRule);
        if (!flag) {
            return ResultData.failure("数据库错误");
        }
        return ResultData.success();
    }
    /**一键开启规则*/
    @Override
    public ResultData openAllRule(OpenAllRuleModel model) {
        Customer customer = SaTokenUtilPy.getCustomer();
        Long customerId = customer.getCustomerId();
        List<Long> holidayIds = new ArrayList<>();
        if (model.getCategoryId() != null) {
            List<Holiday> holidayList = new ArrayList<>();
            if (model.getCategoryId() == 1) {
                holidayList = holidayService.list(new LambdaQueryWrapper<Holiday>()
                        .in(Holiday::getCategoryId, Arrays.asList(1, 2, 3, 4))
                        .eq(Holiday::getValidFlag, VALID_TRUE)
                        .orderByDesc(Holiday::getCreateTime)
                );
                log.info("获取所有节假日id:{}", holidayIds);
            } else if (model.getCategoryId() == 2) {
                holidayIds.add(6L);
            } else {
                holidayList = holidayService.list(new LambdaQueryWrapper<Holiday>()
                        .eq(Holiday::getCategoryId, model.getCategoryId())
                        .eq(Holiday::getValidFlag, VALID_TRUE)
                        .orderByDesc(Holiday::getCreateTime)
                );
            }
            if (model.getCategoryId() != 2) {
                holidayIds = Optional.ofNullable(holidayList)
                        .orElse(Collections.emptyList())
                        .stream()
                        .map(Holiday::getHolidayId)
                        .collect(Collectors.toList());
            }
        }
        List<SmsRule> smsRuleList = list(new LambdaQueryWrapper<SmsRule>()
                .eq(model.getHolidayId()!=null,SmsRule::getHolidayId,model.getHolidayId())
                .in(model.getCategoryId()!=null&&holidayIds.size()>0,SmsRule::getHolidayId,holidayIds)
                .eq(model.getCategoryId()!=null&&holidayIds.size()==0,SmsRule::getHolidayId,-1)
                .eq(SmsRule::getValidFlag,VALID_FALSE)
                .eq(SmsRule::getCustomerId,customerId)
        );
        if (smsRuleList.size()>0){
            smsRuleList.forEach(smsRule -> {
                SmsRule rule = getById(smsRule.getRuleId());
                rule.setValidFlag(VALID_TRUE);
                updateById(rule);
            });
        }
        return ResultData.success();
    }
}
